package com.kpx.app.view;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.andview.refreshview.XRefreshView;
import com.kpx.app.Application;
import com.kpx.app.R;
import com.kpx.app.activity.ActivityTaskDetail;
import com.kpx.app.adapter.TaskAdapter;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.ListBean;
import com.kpx.app.bean.MenuBean;
import com.kpx.app.bean.TaskBean;
import com.kpx.app.configs.Constants;
import com.kpx.app.fragment.FragmentMyTask;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.uiutils.DisplayUtil;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.wigdet.PopShowMenu;
import com.kpx.app.wigdet.PopShowTaskMenu;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/2/26.
 */

public class ViewTaskDating extends LinearLayout {

    @BindView(R.id.lv_task_show)
    ListView lvTaskShow;
    @BindView(R.id.custom_view)
    XRefreshView outView;
    @BindView(R.id.txt_empty_mention)
    TextView txtEmptyMention;
    @BindView(R.id.ll_pop_category)
    LinearLayout llPopCategory;
    @BindView(R.id.ll_paixu)
    LinearLayout llPaixu;
    @BindView(R.id.ll_filter)
    LinearLayout llFilter;
    @BindView(R.id.pop_show)
    View pop_show;
    private Context context;
    private boolean isRefresh;
    private int pageNow = 1;
    private List<TaskBean> taskBeans = new ArrayList<>();
    private double totalPage;
    private TaskAdapter adapter;
    private double pageSize;
    private ArrayList<MenuBean> menus = new ArrayList<>();
    private ArrayList<MenuBean> sortings = new ArrayList<>();
    private ArrayList<MenuBean> filters = new ArrayList<>();
    private ArrayList<MenuBean> categerys = new ArrayList<>();
    private PopShowTaskMenu pop;
    private MenuBean sort;
    private MenuBean filter;
    private MenuBean categery;
    private int popType = -1;
    private View viewroot;
    private boolean doChange = true;
    private FragmentMyTask fragmentMyTask;
    private boolean isreQuesting = false;

    public ViewTaskDating(Context context, FragmentMyTask fragmentMyTask) {
        super(context);
        this.fragmentMyTask = fragmentMyTask;
        initView(context);
    }

    public ViewTaskDating(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public ViewTaskDating(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }


    private void initView(final Context context) {
        this.context = context;
        viewroot = View.inflate(context, R.layout.view_task_dating, this);
        ButterKnife.bind(viewroot);
        initRefreshView();
        setData(context);
        handler.sendEmptyMessageDelayed(0, 1000);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (doChange && taskBeans != null && taskBeans.size() > 0) {
                adapter.notifyDataSetChanged();
            }
            handler.sendEmptyMessageDelayed(0, 1000);
        }
    };

    /**
     * 设置数据
     *
     * @param context
     */
    private void setData(final Context context) {
        String[] str_sorts = context.getResources().getStringArray(R.array.sort);
        int[] id_sorts = context.getResources().getIntArray(R.array.sort_id);
        String[] str_filter = context.getResources().getStringArray(R.array.filter);
        int[] id_filter = context.getResources().getIntArray(R.array.filter_id);
        for (int i = 0; i < str_sorts.length; i++) {
            MenuBean m = new MenuBean();
            m.setName(str_sorts[i]);
            m.setDmId(id_sorts[i] + "");
            sortings.add(m);
        }
        for (int i = 0; i < str_filter.length; i++) {
            MenuBean m = new MenuBean();
            m.setName(str_filter[i]);
            m.setDmId(id_filter[i] + "");
            m.setSelected(i == 0);
            filters.add(m);
        }

        MenuBean m = new MenuBean();
        m.setName("全部");
        m.setDmId("0");
        m.setSelected(true);
        MenuBean m2 = new MenuBean();
        m2.setName("默认推荐");
        m2.setDmId("0");
        m2.setSelected(true);
        sortings.add(0, m2);
        categerys.add(m);
        categery = m;
        sort = sortings.get(0);
        filter = filters.get(0);
        //商品列表的上下拉刷新操作
        outView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                pageNow = 1;
                getTasks();// 获取数据
            }

            @Override
            public void onLoadMore(boolean isSlience) {
                isRefresh = false;
                if (pageNow >= totalPage) {
                    ToastUtil.getInstance().showToast(context, "没有更多了");
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            outView.stopLoadMore();
                        }
                    }, 600);
                } else {
                    pageNow++;
                    getTasks();// 获取数据
                }
            }
        });
        adapter = new TaskAdapter(context, taskBeans, R.layout.item_task_main_show, fragmentMyTask, 0);
        lvTaskShow.setAdapter(adapter);
        lvTaskShow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.KEY_TASK_BEAN, taskBeans.get(position));
                ActivityTaskDetail.intype = ActivityTaskDetail.DATING_TYPE_IN;
                IntentUtil.gotoActivity(context, ActivityTaskDetail.class, bundle);
            }
        });
        isRefresh = true;
        getTasks();
    }

    private void getTasks() {
        if (isreQuesting) {
            return;
        }
        isreQuesting = true;
        ((ActivityBase) context).showLoadingDialog();
        MyHashMap map = new MyHashMap();

        //sorting,cateId,checkId,pageIndex,pageSize
//        sorting 排序 (1：佣金由高到低，2：佣金由低到高，3：等级要求由高到低，4：等级要求由低到高)
//        checkId	筛选条件(NULL 或者 0 为全部，1 表示 适合我的，2 表示我的专属)
//        cateId  分类字典的列表值ID
        map.put("sorting", sort.getDmId());
        map.put("cateId", categery.getDmId());
        map.put("checkId", filter.getDmId());
        map.put("pageIndex", pageNow + "");
        map.put("pageSize", "20");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                isreQuesting = false;
                ((ActivityBase) context).dissmissLoadingDialog();
                if (isRefresh) {
                    outView.stopRefresh();
                } else {
                    outView.stopLoadMore();
                }
                if (result.getCode() == 0) {
                    ArrayList<TaskBean> getData = (ArrayList<TaskBean>) result.getData();
                    if (isRefresh) {
                        taskBeans.clear();

                    } else {
                        if (getData.size() % pageSize != 0) {
                        }
                    }
                    totalPage = result.getPage().getPageSize();
                    outView.setAutoLoadMore(true);
                    outView.setPullRefreshEnable(true);
                    outView.setPullLoadEnable(true);
                    taskBeans.addAll(getData);
                    adapter.setData(taskBeans);
                    if (taskBeans.size() == 0) {
                        txtEmptyMention.setText("暂无相关任务信息");
                        txtEmptyMention.setOnClickListener(null);
                        txtEmptyMention.setVisibility(View.VISIBLE);
                    } else {
                        txtEmptyMention.setVisibility(View.GONE);
                    }
                } else {
                    ToastUtil.getInstance().showToast(context, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                isreQuesting = false;
                ((ActivityBase) context).dissmissLoadingDialog();
                if (isRefresh && taskBeans.size() == 0) {
                    outView.stopRefresh();
                    txtEmptyMention.setVisibility(View.VISIBLE);
                    txtEmptyMention.setText("获取信息失败，点击重试");
                    txtEmptyMention.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            getTasks();// 获取数据
                        }
                    });
                } else {
                    outView.stopLoadMore();
                }
                ToastUtil.getInstance().showToast(context, error);
            }

        }, TaskBean.class, HttpDataRequest.TYPE_LIST).POST(HttpDataReqUrl.URL_POST_TASK_LIST, true, map);

    }

    /**
     * 初始化上下拉刷新
     */
    private void initRefreshView() {
        outView.setPullLoadEnable(true);
        outView.setPinnedTime(1000);
        outView.setAutoLoadMore(true);
//		outView.setCustomHeaderView(new CustomHeader(this));
//		outView.setCustomHeaderView(new XRefreshViewHeader(this));
        outView.setMoveForHorizontal(true);
//        outView.setCustomFooterView(new CustomerFooter(this));
//		outView.setPinnedContent(true);
        /**
         *scrollState有三种状态，分别是SCROLL_STATE_IDLE、SCROLL_STATE_TOUCH_SCROLL、SCROLL_STATE_FLING
         *SCROLL_STATE_IDLE是当屏幕停止滚动时
         *SCROLL_STATE_TOUCH_SCROLL是当用户在以触屏方式滚动屏幕并且手指仍然还在屏幕上时（The user is scrolling using touch, and their finger is still on the screen）
         *SCROLL_STATE_FLING是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时（The user had previously been scrolling using touch and had performed a fling）
         */
        outView.setOnAbsListViewScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case SCROLL_STATE_IDLE:
                        doChange = true;
                        break;
                    case SCROLL_STATE_TOUCH_SCROLL:
                    case SCROLL_STATE_FLING:
                        doChange = false;
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    @OnClick({R.id.ll_pop_category, R.id.ll_paixu, R.id.ll_filter})
    public void onClick(final View view) {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
        }
        switch (view.getId()) {
            case R.id.ll_paixu:
                popType = 1;
                menus = sortings;
                showPop(view);
                break;
            case R.id.ll_pop_category:
                popType = 2;
                if (categerys.size() <= 1) {
                    UserInfoUtils.getTaskCategerys(context, 1, new UserInfoUtils.OnGetCategerysBackListener() {
                        @Override
                        public void back(ArrayList<MenuBean> menus) {
                            if (menus != null) {
                                categerys.addAll(menus);
                                ViewTaskDating.this.menus = categerys;
                                showPop(view);
                            }
                        }
                    });
                } else {
                    menus = categerys;
                    showPop(view);
                }
                break;
            case R.id.ll_filter:
                popType = 3;
                menus = filters;
                showPop(view);
                break;
        }

    }

    private void showPop(View view) {
        if (pop == null) {
            pop = new PopShowTaskMenu(context, menus, DisplayUtil.getScreenWidth(context), new PopShowTaskMenu.OnSelectClicListener() {
                @Override
                public void onClick(MenuBean bean) {
                    switch (popType) {
                        case 1:
                            sort = bean;
                            break;
                        case 2:
                            categery = bean;
                            break;
                        case 3:
                            filter = bean;
                            if (!filter.getDmId().equals("0") && !UserInfoUtils.isUserLogin()) {
                                UserInfoUtils.showLoginDialog(context, "请先登录", 0);
                                return;
                            }
                            break;
                    }
                    isRefresh = true;
                    pageNow = 1;
                    getTasks();
                }
            });
        }
        if (pop != null) {
            switch (popType) {
                case 1:
                    pop.setData(menus, 2);
                    break;
                case 2:
                    pop.setData(menus, 4);
                    break;
                case 3:
                    pop.setData(menus, 3);
                    break;
            }
            pop.showAsDropDown(pop_show);
            backgroundAlpha(0.5f);
            pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    backgroundAlpha(1f);
                }
            });
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = ((Activity) context).getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        ((Activity) context).getWindow().setAttributes(lp);
    }

    public void showCategery(MenuBean b) {
        categery = b;
        isRefresh = true;
        pageNow = 1;
        getTasks();
    }

    public void refreshData() {
        isRefresh = true;
        pageNow = 1;
        getTasks();
    }
}
